#include <qDebug>
#include "localTcpServer.h"
#include "logger.h"

LocalTcpServer::LocalTcpServer()
{
    myServer = nullptr;
    m_host = "";
    m_port = 0;
    m_threadNum = 1;
}

LocalTcpServer::~LocalTcpServer()
{
    stop();
}

bool LocalTcpServer::init(const int port, const std::string host, const int threadNum)
{
    m_host = host;
    m_port = port;
    m_threadNum = threadNum;

    myServer = new hv::TcpServer;
    if(myServer == nullptr)
    {
        return false;
    }
    return true;
}

bool LocalTcpServer::start()
{
    if(myServer == nullptr)
    {
        return false;
    }

    int listenfd = myServer->createsocket(m_port, m_host.c_str());
    if (listenfd < 0) {
        LOG(ERROR) <<"createsocket err "<<" ip:" <<  m_host.c_str()<<" port:" <<m_port << std::endl;
        return false;
    }

    myServer->onConnection = [](const hv::SocketChannelPtr& channel) {
        std::string peeraddr = channel->peeraddr();
        if (channel->isConnected()) {
            LOG(INFO) <<"connected to " << peeraddr <<", connfd=" <<channel->fd() << std::endl;
        }else {
            LOG(INFO) <<"disconnected to " << peeraddr <<", connfd=" <<channel->fd() << std::endl;
        }
    };

    myServer->onMessage = [this](const hv::SocketChannelPtr& channel, hv::Buffer* buf) {
        if(this->callBack){
            this->callBack((const char*)buf->data(), buf->size());
        }
    };

    myServer->onWriteComplete = [](const hv::SocketChannelPtr& channel, hv::Buffer* buf) {
         //qDebug("> %.*s\n", (int)buf->size(), (char*)buf->data());
    };

    myServer->setThreadNum(m_threadNum);
    myServer->start();
    return true;
}

void LocalTcpServer::stop()
{
    SAFE_DELETE(myServer);
    myServer = nullptr;
}

void LocalTcpServer::registeCb(std::function<void (const char *, int)> cb)
{
    callBack = cb;
}

void LocalTcpServer::activeSend(char *data, size_t sz)
{
    myServer->broadcast(data, sz);
}
